from rest_framework.response import Response
from rest_framework.views import APIView
from api.models import Depart
from api import models
from rest_framework import serializers, viewsets
from rest_framework.exceptions import NotFound

# ModelSerializer
class DepartSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Depart
        # fields = "__all__"
        # 指定字段
        fields = ["title", "count", "order", "id"]

class DepartView(viewsets.ModelViewSet):
    queryset = Depart.objects.all()  # 指定查询集
    serializer_class = DepartSerializer
    def post(self, request, *args, **kwargs):
        # 使用 DepartSerializer 处理请求数据
        serializer = DepartSerializer(data=request.data)

        # 验证数据
        if serializer.is_valid():
            # 保存验证后的数据到数据库
            serializer.save()
            return Response('Depart 添加成功')
        else:
            return Response(serializer.errors, status=400)



class DepartDetailView(viewsets.ModelViewSet):
    queryset = Depart.objects.all()  # 指定查询集
    serializer_class = DepartSerializer
    def get(self, request, depart_id, *args, **kwargs):
        try:
            # 通过主键（ID）查找要获取的 Depart 对象
            depart = models.Depart.objects.get(id=depart_id)
        except models.Depart.DoesNotExist:
            raise NotFound("Depart 对象不存在")

        # 使用 DepartSerializer 序列化 Depart 对象
        serializer = DepartSerializer(depart)
        return Response(serializer.data)

    def put(self, request, depart_id, *args, **kwargs):
        try:
            # 通过主键（ID）查找要更新的 Depart 对象
            depart = models.Depart.objects.get(id=depart_id)
        except models.Depart.DoesNotExist:
            raise NotFound("Depart 对象不存在")

        # 使用 DepartSerializer 将请求数据更新到 Depart 对象
        serializer = DepartSerializer(depart, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors, status=400)

    def delete(self, request, depart_id, *args, **kwargs):
        try:
            # 通过主键（ID）查找要删除的 Depart 对象
            depart = models.Depart.objects.get(id=depart_id)
        except models.Depart.DoesNotExist:
            raise NotFound("Depart 对象不存在")

        # 删除 Depart 对象
        depart.delete()

        return Response("Depart 删除成功")

